﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows;


namespace VoiceTestPlatform
{
    public class SerialPortHelper
    {
        static object locker = new object();
        static SerialPortHelper interInstance;
        public static SerialPortHelper Instance
        {
            get
            {
                if (interInstance == null)
                {
                    lock (locker)
                    {
                        if (interInstance == null)
                        {
                            interInstance = new SerialPortHelper();
                        }
                    }
                }

                return interInstance;
            }
        }

        public void InitPort()
        {
           // SerialPort serialPort1 = new SerialPort();

        }

        public ObservableCollection<string> GetPortNames()
        {
            ObservableCollection<string> SerialPorts = new ObservableCollection<string>();
            string[] ports = SerialPort.GetPortNames();
            if (ports == null)
            {
                return null;
            }
            foreach (var item in ports)
            {
                SerialPorts.Add(item);
            }
            return SerialPorts;
        }

        public SerialPort OpenPort(string port, int baudrate, int DataBit, StopBits sb, Parity parity)
        {
            SerialPort curport = new SerialPort();
            curport.PortName = port;
            curport.BaudRate = baudrate;
            curport.DataBits = DataBit;

            if ((sb < StopBits.One) || (sb > StopBits.OnePointFive))
            {
                sb = StopBits.One;
            }

            curport.StopBits = sb;
            curport.Parity = parity;

            try
            {
                curport.Open();
            }
            catch (Exception ex)
            {
                curport = null;
                MessageBox.Show(ex.Message);
                return null;
            }
            return curport;
        }

        public bool IsPortOpened = false;

        //SerialPort curport = null;
        //public SerialPort CurrentPort { get { return curport; } }

        static SerialPortHelper()
        {
            SerialPortString = new StringBuilder();
        }

        public static StringBuilder SerialPortString;
    }
}
